<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="用户账号">
      <el-input v-model="form.name" disabled/>
    </el-form-item>
    <el-form-item label="原金额">
      <el-input v-model="form.Ymoney" disabled/>
    </el-form-item>
    <el-form-item label="充值金额">
      <el-input-number v-model="form.money" :min="0" :max="1000" @change="handleChange"/>
    </el-form-item>
    <el-form-item label="最后金额">
      <el-input v-model="form.Rmoney" disabled/>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">确认提交</el-button>
      <el-button @click="emit('close-dialog')">取消</el-button>
    </el-form-item>

  </el-form>
</template>

<script lang="ts" setup>
import {reactive, onMounted, watch} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import { defineProps } from 'vue';
import { defineEmits } from 'vue';
import router from "@/router";

const emit = defineEmits(['close-dialog'])

const props = defineProps({
  UID: String,
  name: String,
  money: String,
  cancel: Boolean,
});

const form = reactive({
  name: '',
  money: 0,
  Ymoney:0,
  Rmoney:0,
})

const rank_changeUrl = 'https://movie.cpb2013.top/admin/rank.php?mode=change' // 替换为你的上传地址

const handleChange = (value: number) => {
  form.Rmoney=form.Ymoney+ value;
}

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()

  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? '女' : '男');
    }
  });
  formData.append('UID',props.UID);
  formData.delete('name');
  formData.delete('Rmoney');
  formData.delete('Ymoney')
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(rank_changeUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('充值成功！')
        emit('close-dialog')
        // this.$emit('close-dialog');
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('充值失败！')
    }
  } catch (error) {
    ElMessage.error('请求失败！')
  }
  closeFullScreen(loading)
}

onMounted(() => {
  // const MID = '06a718d656fac9f771507e1872adc838'; // replace with actual MID
  form.name=props.name;
  form.Rmoney=parseFloat(props.money);
  form.Ymoney=parseFloat(props.money);
});

watch(() => props.UID, () => {
  form.name=props.name;
  form.Rmoney=parseFloat(props.money);
  form.Ymoney=parseFloat(props.money);
});

watch(() => props.money, () => {
  form.name=props.name;
  form.Rmoney=parseFloat(props.money);
  form.Ymoney=parseFloat(props.money);
});

</script>
